from typing import Annotated 
from datetime import timedelta 

from fastapi import APIRouter, Depends , HTTPException 
from fastapi.security import OAuth2PasswordRequestForm

from service.auth import authenticate_user , create_access_token
from model.token import Token 
from model.user import User 
from config.settings import get_settings 


router = APIRouter(prefix='/login') 
settings = get_settings()

@router.post('token')
async def login(form_data:Annotated[OAuth2PasswordRequestForm, Depends()] ) -> Token: 
    user = authenticate_user(form_data.username, form_data.password) 
    if not user: 
        raise HTTPException(status_code=401, detail='Incorrect username or password', headers={'WWW-Authenticate': 'Bearer'}) 

    access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
    access_token = create_access_token(data={'sub': user.username}, expires_delta=access_token_expires)

    return Token(access_token=access_token, token_type='Bearer')

